
package org.web.base.domain.config;

import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;
import org.web.base.domain.exception.ResultMessageEnum;
import org.web.base.domain.exception.ServiceException;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.web.base.domain.helper.ServiceExceptionHelper;

public class GlobalString2DateConvert implements Converter<String, Date> {

    private static String[] DATE_FORMATS = {"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd", "yyyy-MM"};

    private static Map<String, String> formatMap = new HashMap<>(4);

    static {
        formatMap.put("yyyy-MM-dd HH:mm:ss", "^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$");
        formatMap.put("yyyy-MM-dd HH:mm", "^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$");
        formatMap.put("yyyy-MM-dd", "^\\d{4}-\\d{1,2}-\\d{1,2}$");
        formatMap.put("yyyy-MM", "^\\d{4}-\\d{1,2}$");
    }

    @Override
    public Date convert(String source) throws ServiceException {
        if (StringUtils.isEmpty(source)) {
            return null;
        }

        source = source.trim();

        if (StringUtils.isEmpty(source)) {
            return null;
        }
        source = source.trim();   //去除首尾空格


        //正则表达式判断是哪一种格式参数
        for (String format : DATE_FORMATS) {
            try {
                String pattern = formatMap.get(format);
                if (pattern != null && source.matches(pattern)) {
                    DateFormat dateFormat = new SimpleDateFormat(format);
                    return dateFormat.parse(source);
                }
            } catch (Exception e) {
                throw ServiceExceptionHelper.buildServiceException(ResultMessageEnum.PARAM_INVALID, "[" + source + "]日期格式不合法。");
            }
        }

        // 如果所有日期格式都无法解析，返回null或抛出异常，根据需要进行处理
        throw ServiceExceptionHelper.buildServiceException(ResultMessageEnum.PARAM_INVALID, "[" + source + "]日期格式不合法。");
    }
}

